import os
import re
import shutil
from datetime import date, timedelta, datetime
from config import store_grib_dir, store_nc_dir
try:
    from log_own import logger
except ImportError:
    import sys
    sys.path.append(".")
    sys.path.append("../")
    sys.path.append("../../")
    from log_own import logger


# 获取5天前的日期
target_date = (datetime.now() - timedelta(days=5))


def delete_dir():
    # 数据存储目录
    for dir in os.listdir(store_grib_dir):
        # 删除5天前的日期数据
        if datetime.strptime(dir, "%Y%m%d").__le__(target_date):
            del_dir = os.path.join(store_grib_dir, dir)
            try:
                shutil.rmtree(del_dir)
                logger.info(f"已删除目录: {del_dir}")
            except Exception as e:
                logger.error(e)


def delete_nc():
    for root, dirs, files in os.walk(store_nc_dir):  # /home/ECMWFdownload/data/netcdf
        for dir in dirs:
            del_dir = os.path.join(root, dir)
            try:
                d = datetime.strptime(dir, "%Y%m%d%H%M%S")
                if d.__le__(target_date):
                    shutil.rmtree(del_dir)
                    logger.info(f"已删除目录: {del_dir}")
            except ValueError:
                continue


def delete_old_data():
    for root, dirs, files in os.walk("/home/ECMWFdownload/data"):  # /home/ECMWFdownload/data/netcdf
        for dir in dirs:
            del_dir = os.path.join(root, dir)
            if re.match("^\\d{8}$", dir):
                d = datetime.strptime(dir, "%Y%m%d")
            elif re.match("^\\d{14}$", dir):
                d = datetime.strptime(dir, "%Y%m%d%H%M%S")
            else:
                continue
            try:
                if d.__le__(target_date):
                    shutil.rmtree(del_dir)
                    logger.info(f"已删除目录: {del_dir}")
            except ValueError as e:
                logger.error(e)
                continue


if __name__ == '__main__':
    pass
    # delete()
    delete_old_data()
